package com.springboot.lotterysystem.controller.handler;

import com.springboot.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import com.springboot.lotterysystem.common.exception.ControllerException;
import com.springboot.lotterysystem.common.exception.ServiceException;
import com.springboot.lotterysystem.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-04-20
 * Time: 21:37
 */
@RestControllerAdvice // 可以捕获全局的异常
public class GlobalException {

    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);

    // 处理service层的异常
    @ExceptionHandler(value = ServiceException.class)
    public CommonResult<?> serviceException(ServiceException e) {
        // 1、打印错误日志
        logger.error("serviceException: ", e);
        // 2、构造错误结果
        return CommonResult.error(
                GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }


    // 处理controller层的异常
    @ExceptionHandler(value = ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e) {
        // 1、打印错误日志
        logger.error("controllerException: ", e);
        // 2、构造错误结果
        return CommonResult.error(
                GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }

    // 针对并未手动捕获到的异常处理
    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> exception(Exception e) {
        // 1、打印错误日志
        logger.error("服务异常: ", e);
        // 2、构造错误结果
        return CommonResult.error(
                GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }
}
